package com.syxbbs.forum.services.Impl;

import com.syxbbs.forum.common.AppResult;
import com.syxbbs.forum.common.ResultCode;
import com.syxbbs.forum.dao.BoardMapper;
import com.syxbbs.forum.exception.ApplicationException;
import com.syxbbs.forum.model.Board;
import com.syxbbs.forum.services.IBoardServive;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
@Slf4j
public class BoardServiceImpl implements IBoardServive {
    @Autowired
    BoardMapper boardMapper;



    @Override
    public List<Board> selectByNum(Integer num) {

        if (num<0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());

        }
        //查询数据库
        List<Board> result = boardMapper.selectByNum(num);
        return result;


    }

//    @Transactional，通过主键寻找板块
    @Override
    public Board selectById(Long id) {
        if(id==null || id<0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
        }
        return boardMapper.selectByPrimaryKey(id);

    }

    //更新帖子数量并且将用户的数目加1
    /*@Transactional*/
    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        if (board==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failure());

        }
        Board updateBoard=new Board();
        updateBoard.setId(board.getId());
        updateBoard.setArticleCount(board.getArticleCount()+1);
        boardMapper.updateByPrimaryKeySelective(updateBoard);
        //更新数据库。



    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null || id<0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        if (board==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failure());

        }
        Board updateBoard=new Board();
        updateBoard.setId(board.getId());
        updateBoard.setArticleCount(board.getArticleCount()-1);
        if (board.getArticleCount()<0){
            board.setArticleCount(0);
        }

        boardMapper.updateByPrimaryKeySelective(updateBoard);

    }
}
